package org.ning;

import org.apache.commons.codec.binary.StringUtils;
import org.ning.http.HttpUtils;
import org.ning.model.TagResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/7/5 10:47
 */
public class DockerUtil {

    static private HttpUtils httpUtils = HttpUtils.getInstance();
    private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void readTags(String library) throws IOException {
        int page = 1;
        boolean process = true;
        boolean hasNext = true;
        while (true){
            if(process){
                TagResult result = httpUtils.getAllTags(library, page);
                printResult(result);
                hasNext = result.getNextUrl()!=null && !"".equals(result.getNextUrl());
                if(result.getNextUrl()!=null&&!"".equals(result.getNextUrl())){
                    System.out.println("输入数字跳页|输入n下一页|输入q退出");
                }
                process = false;
            }

            String command = reader.readLine();
            if("".equals(command))
                continue;
            if(command.trim().equals("q"))
                break;
            if(command.trim().equals("n")){
                if(hasNext){
                    page ++;
                    process = true;
                    continue;
                }else {
                    System.out.println("已经到底了!");
                    System.out.println("输入数字跳页|输入n下一页|输入q退出");
                    process= false;
                    continue;
                }

            }

            try{
                int pageNum = Integer.parseInt(command);
                if(pageNum<=0){
                    System.out.println("页数不合法");
                    process = false;
                }
                page = pageNum;
                process = true;

            }catch (NumberFormatException ignore){
                System.out.println("页数不合法");
                process = false;
            }

        }


    }


    public static void main(String[] args) throws IOException {


        while (true){
            System.out.print("请输入要搜索的镜像ID(q退出):");

            String command= reader.readLine().trim();
            if("".equals(command))
                continue;
            if("q".equals(command))
                break;
            readTags(command);

        }

    }

    private static void printResult(TagResult result){


        result.getTagList().forEach(tag -> {
            System.out.printf("%-25s|%-10s|%8s|%s\n", tag.getName(), tag.getUpdateTime(), tag.getBetween(), tag.getPullCommand());
        });
        System.out.printf("=====================共%d个tag 当前页数%d 共%d页=====================\n", result.getTotal(), result.getCurrentPage(), result.getTotalPage());
    }


}
